package com.huawei.leetcode;

import java.util.Map;

public class Code724 {

    public static void main(String[] args) {
        System.out.println(pivotIndex(new int[]{1, 7, 3, 6, 5, 6}));

        System.out.println(pivotIndex2(new int[]{1, 7, 3, 6, 5, 6}));
    }
    public static int pivotIndex2(int[] nums) {
        int n = nums.length;
        int[] sum = new int[n + 1];
        for (int i = 0; i < n; i++) {
            sum[i + 1] = sum[i] + nums[i];
        }
        for (int i = 0; i < n; i++) {
            if (sum[i] == sum[n] - sum[i + 1]) {
                return i;
            }
        }
        return -1;
    }
    public static int pivotIndex(int[] nums) {
        int sumTotal = sumTotal(nums);
        for (int i = 0; i < nums.length; i++) {
            int sunHalf = sunHalf(i, nums);
            if( sunHalf == (sumTotal-nums[i]-sunHalf) ){
                return i;
            }
        }
        return -1;
    }

    private static int sunHalf(int j,int[] nums) {
        int ans = 0;
        for (int k = 0; k < j; k++) {
            ans += nums[k];
        }
        return ans;
    }

    private static int sumTotal(int[] nums) {
        int ans = 0;
        for (int i = 0; i < nums.length; i++) {
            ans += nums[i];
        }
        return ans;
    }
}
